#include "Grid.h"
#include "ImageLoader.hpp"
#include "GameWorld.h"

Grid::Grid()
{
	mGridSize.h = 0;
	mGridSize.w = 0;
}

Grid::Grid(const std::string& filename)
{
	mGridSize.h = 0;
	mGridSize.w = 0;
	LoadGrid(filename);
}

void Grid::LoadGrid(const string& filename)
{
	// set grid size

	// load our map
	ifstream file;
	file.open(filename.c_str());
	assert("Unable to load level " && file.is_open());

	int width, height;
	file >> width;
	file >> height;

	mGridSize.w = width;
	mGridSize.h = height;

	// load in file data to the grid
	string data;
	int ignored = ImageManager->GetImageID("ignored_tile");
	mGrid.resize(mGridSize.h + 1);
	for(int h = 0; h < mGridSize.h; ++h)
	{
		mGrid[h].resize(mGridSize.w + 1);
		for(int w = 0; w < mGridSize.w; ++w)
		{
			// insert layers
			data = "reset";
			while(data != "->")
			{
				file >> data;
				if(data != "->" && atoi(data.c_str()) != ignored)
					mGrid[h][w].push_back(atoi(data.c_str()));
			}
		}
	}
	file.close();
}

void Grid::Render()
{

	int width = (ClipPlane->GetWidth() / 32) + 1;
	int height = (ClipPlane->GetHeight() / 32) + 2;
	int startX = ClipPlane->GetX() / 32;
	int startY = ClipPlane->GetY() / 32;

	list<int>::const_iterator iter;
	for(int h = startY; h < height + startY && h < mGridSize.h; ++h)
		for(int w = startX; w < width + startX && w < mGridSize.w; ++w)
			for(iter = mGrid[h][w].begin(); iter != mGrid[h][w].end(); ++iter)
				Entity::RenderImage(w * TILE_DIMENSIONS, h * TILE_DIMENSIONS, (*iter), ClipPlane);


}

void Grid::SaveGrid(const string& filename)
{
	// Open a file that we can write to
	ofstream file;
	file.open(filename.c_str());
	assert(file);

	// Simply insert the level map into the file
	if(file.is_open())
	{
		file << mGridSize.w << " " << mGridSize.h;
		list<int>::iterator iter;
		for(int y = 0; y < mGridSize.h; ++y)
		{
			for(int x = 0; x < mGridSize.w; ++x)
			{
				for(iter = mGrid[y][x].begin(); iter != mGrid[y][x].end(); ++iter)
					file << (*iter) << " ";

				file << " -> ";
			}

			file << "\n";
		}
		file.close();
	}

}